<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>注册</title>
    <link rel="stylesheet" href="/libs/bootstrap/css/bootstrap.min.css" />
    <script src="/libs/jquery-3.4.1.min.js"></script>
    <style>
      .center {
        width: 500px;
        margin: 0 auto;
      }
    </style>
  </head>
  <body>
    <div class="center">
      <h1>注册</h1>
      <form>
        <div class="form-group">
          <label for="user-input">用户名</label>
          <input
            type="text"
            class="form-control"
            id="user-input"
            placeholder="请输入用户名"
          />
        </div>
        <div class="form-group">
          <label for="pwd-input1">密码</label>
          <input
            type="password"
            class="form-control"
            id="pwd-input1"
            placeholder="请输入密码"
          />
        </div>
        <div class="form-group">
          <label for="pwd-input2">确认密码</label>
          <input
            type="password"
            class="form-control"
            id="pwd-input2"
            placeholder="再次输入密码"
          />
        </div>
        <div class="form-group">
          <label for="avatar-input">头像</label>
          <input type="file" id="avatar-input" />
          <p class="help-block">上传头像图片</p>
        </div>
        <button type="submit" class="btn btn-default">注册</button>
      </form>
    </div>
    <script>
      $("form").on("submit", function(e) {
        e.preventDefault();
        var username = $("#user-input")
          .val()
          .trim();
        var pwd1 = $("#pwd-input1")
          .val()
          .trim();
        var pwd2 = $("#pwd-input2")
          .val()
          .trim();
        // 这里可以来一些简单的正则验证用户名密码规则
        if (pwd1 !== pwd2) {
          alert("两次输入密码不一致");
          return;
        }
        const avatar = $("#avatar-input")[0].files[0];
        // 提交：上传用户名密码和头像
        const fd = new FormData();
        fd.append("username", username);
        fd.append("password", pwd1);
        fd.append("avatar", avatar);

        $.ajax({
          url: "/api/user/register",
          method: "POST",
          data: fd,
          contentType: false,
          processData: false,
          success: resp => {
            if (resp.code === 200) {
              alert(resp.body.msg + "，即将跳转登录页");
              window.location.href = "./login.html";
            } else {
              alert(resp.body.msg);
            }
          }
        });
      });
    </script>
  </body>
</html>
